'use client';

import { useChat } from '@ai-sdk/react';
import { useRef, useEffect } from 'react';
import EastIcon from '@mui/icons-material/East';
import { useState } from 'react';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import ChatMessage from '@/compontents/ChatMessage';
import UploadContainer from '@/compontents/UploadContainer';

export default function Page() {
  // 删除或注释掉下面这行重复声明
  // const chat_id = useParams();

  const params = useParams();
  const chat_id = params['chat-id']; // 统一使用这种方式获取参数
  console.log(chat_id)

  const { data: chat } = useQuery({//获取聊天标题
    queryKey: ['chat', chat_id],
    queryFn: async () => {
      return axios.post('/api/get-chat', {
        chat_id: chat_id
      })
    }
  })

  const { data: previousMessages } = useQuery({//这里接受聊天记录
    queryKey: ['messages', chat_id],
    queryFn: () => {
      return axios.post(`/api/get-messages`, {
        chat_id: chat_id,
        chat_user_id: chat?.data?.userId
      })
    },
    enabled: !!chat?.data?.id
  })
  const handleFirstMessage = async (model: string) => {//发送第一条消息
    if (chat?.data?.title && previousMessages?.data?.length === 0) {
      console.log('model', model, chat?.data)
      await append({
        role: 'user',
        content: chat?.data?.title
      }), {
        model: model,
        chat_id: chat_id,
        chat_user_id: chat?.data?.userId
      }
    }
  }

  useEffect(() => {
    setModel(chat?.data?.model)
    handleFirstMessage(chat?.data?.model)
  }, [chat?.data?.title, previousMessages])//当消息获取后，如果没有消息，就发送第一条消息,



  const [model, setModel] = useState("deepseek-v3");
  const handleChangemodel = () => {
    setModel(model === 'deepseek-r1' ? 'deepseek-v3' : 'deepseek-r1')
  }

  const { messages, input, handleInputChange, handleSubmit, append } = useChat({//这里实现了上传聊天记录,和得到ai的回答
    body: {
      model: model,
      chat_id: chat_id,
      chat_user_id: chat?.data?.userId
    },
    initialMessages: previousMessages?.data//将聊天记录传给后端的ai
  });
  useEffect(() => {
    console.log('messages', messages)
  }, [messages])



  const endRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (endRef.current) {
      endRef?.current?.scrollIntoView({ behavior: 'smooth' })
    }
  })

  return (
    <div className='flex flex-col h-screen justify-between'>
      {/* 消息区域 - 添加固定高度和滚动 */}
      <div className="flex-1 overflow-y-auto p-4 w-full max-w-4xl mx-auto">
        <div className="space-y-4 min-h-[calc(100vh-200px)]">
          {messages.map(message => (
            <div
              key={message.id}
              className={`flex flex-row ${message?.role === 'assistant' ? 'justify-start' : 'justify-end'} mb-4`}>
              <div className={`max-w-[80%] rounded-2xl px-4 py-3 ${message?.role === 'assistant' ?
                'bg-blue-100 rounded-bl-none' :
                'bg-indigo-100 rounded-br-none'}`}>
                <div className={`text-gray-800 ${message?.role === 'assistant' ? 'text-left' : 'text-right'}`}>
                  <ChatMessage message={message.content} role={message.role} />
                </div>
              </div>
            </div>
          ))}
          <div ref={endRef} className="h-8" />
        </div>
      </div>

      {/* 输入框区域 - 恢复原有输入框代码 */}
      <div className="flex flex-col items-center justify-center mt-4 shadow-lg border-[1px] border-gray-300 h-32 rounded-lg w-full max-w-4xl mx-auto bg-white">
        <textarea
          className="w-full rounded-lg p-3 h-30 focus:outline-none resize-none
                    placeholder-gray-400 text-gray-700
                    focus:ring-2 focus:ring-blue-500 focus:border-transparent
                    transition-all duration-200"
          value={input}
          onChange={handleInputChange}
          placeholder="输入您的问题..."
        />

        <div className="flex flex-row items-center justify-between w-full h-12 mb-2 px-3">
          <div className="flex items-center gap-2 h-full">
            <UploadContainer />
            <div
              className={`flex items-center justify-center h-full rounded-lg border-[1px] px-2 py-1 cursor-pointer 
                       ${model === 'deepseek-r1' ? 'border-blue-300 bg-blue-200' : "border-gray-300"}
                       hover:bg-gray-100 transition-colors duration-200`}
              onClick={handleChangemodel}
            >
              <p className="text-sm">深度思考(R1)</p>
            </div>
          </div>
          <div
            className="flex items-center justify-center border-2 mr-4 border-black p-1 rounded-full
                    hover:bg-black hover:text-white transition-colors duration-200"
            onClick={handleSubmit}
          >
            <EastIcon className="w-5 h-5" />
          </div>
        </div>
      </div>
    </div>
  );
}